<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.proCode"
        size="small"
        placeholder="商品编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.goodsBrand"
        size="small"
        placeholder="商品品牌"
        style="width: 200px;margin-left:2%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.infoName"
        size="small"
        placeholder="商品名称"
        style="width: 200px;margin-left:2%"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <p style="display:inline-block;margin-left:2%">商品类型：</p>
      <el-select
          size="small"
          placeholder="全部"
          clearable
          class="filter-item"
          style="width: 130px"
          v-model="depValue"
        >
          <el-option v-for="item in deps" :key="item.id" :label="item.name" :value="item.catId"/>
        </el-select>
      <el-button
        size="small"
        class="filter-item"
        type="success"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      size="small"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        :class-name="getSortClass('id')"
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品编码" width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.proCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" min-width="200px" align="center">
        <template slot-scope="scope" style="display:flex; justify-content:space-around">
          <div style="display:flex; justify-content:space-around;width:100%;height:100%">
            <div style="width:40%;height:100%">
              <img style="width:70%;height:70%" @click="showBig(scope.row)" :src="scope.row.imageUrl">
            </div>
            <el-dialog append-to-body :visible.sync="dialogible">
              <img width="100%" :src="dialogImage" alt="">
            </el-dialog>
            <div style="width:40%;height:100%;display:flex;flex-direction:column;align-items:center">
              <p style="display:block;width:100%; height: 50%">{{scope.row.infoName}}</p>
              <p style="display:block;width:100%; height: 50%">{{scope.row.title}}</p>
            </div>       
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.goodsBrand }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.catName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="销售价/市场价" width="300px" align="center">
        <template slot-scope="scope">
          <span style="display:inline-block;width:100%" v-for="(item,index) in scope.row.proPriceVosList" :key="index">市场价：￥{{item.proMarketPrice }}&nbsp;&nbsp;&nbsp;&nbsp;销售价：￥{{item.proSellPrice }}</span>
          <!-- <span style="display:inline-block;width:100%" v-for="(res,i) in scope.row.proPriceVosList" :key="i">采购价：￥{{res.proPurchansePrice }}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="商品状态" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==0?'删除':scope.row.status==1?'正常':'下架' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"  
        width="200px"
        class-name="small-padding fixed-width"
      > 
        <template slot-scope="{ row }">
          <el-button
            size="small"
            align="center"
            type="primary"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      @close="loadPage"
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 100%;"
      >
        <a-steps :current="current">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" />
        </a-steps>
        <div class="steps-content">
          <el-form-item v-if="current==0" style="width:50%;margin-left:25%;margin-top:5%" label="商品展示图:">
            <el-upload
              action="http://10.0.0.74:8090/uploadImgUrl"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :fileList="fileList"
              :limit = '1'
              :on-remove="handleRemove"
              :http-request="customRequest">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog append-to-body :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item v-if="current==1" style="width:80%;margin-left:10%;margin-top:5%" label="商品轮播图:">
            <el-upload
              action="http://10.0.0.74:8090/uploadImgUrl"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview1"
              :on-remove="handleRemove1"
              :fileList="fileList1"
              :http-request="customRequest1">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog append-to-body :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item v-if="current==2" style="width:80%;margin-left:10%;margin-top:5%" label="商品详情图:">
            <el-upload
              action="http://10.0.0.74:8090/uploadImgUrl"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview2"
              :on-remove="handleRemove2"
              :fileList="fileList2"
              :http-request="customRequest2">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog append-to-body :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </div>
        <div class="steps-action">
          <a-button
            v-if="current>0"
            style="margin-left: 8px"
            @click="prev"
          >
            上一步
          </a-button>
          <a-button
            v-if="current < steps.length - 1"
            type="primary" @click="next"
          >
            下一步
          </a-button>
          <a-button
            v-if="current == steps.length - 1"
            type="primary"
            @click="updateData()"
          >
            提交
          </a-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {delImg,delDetailsImg, addImg,updateImg, commodityList,getSearchList,getImg1 } from '@/api/commodities'// 异步请求 delLly
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // 分页插件

const calendarTypeOptions = [
  { key: 0, display_name: '无效' },
  { key: 1, display_name: '正常' },
  { key: 2, display_name: '锁定' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  inject:["reload"],
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dialogible:false,
      dialogImage:'',
      dialogImageUrl: '',
      dialogVisible: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        proCode: '',
        goodsBrand: '',
        infoName:'',
        sort: '+id'
      },
      deps:[],
      depValue:'',
      fileList:[],
      fileList1:[],
      fileList2:[],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        provinceCode: '',
        cityCode: '',
        countyCode: '',
        province: '',
        city: '',
        county: '',
        approle: ''
      },
      proId:'',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      exhibitionImg:'',
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      liaUserName: '',
      liaUserList: {},
      liaUser: null,
      current: 0,
      aaImg:[],
      detailsImg:[],
      xiangqing:'',
      lunbo:'',
      steps: [{
        title: '商品展示图',
      }, {
        title: '商品轮播图',
      }, {
        title: '商品详情图',
      }],
    }
  },
  created() {
    this.getList()
    this.getSearch() 
    // this.getImg()
  },
  methods: {
    showBig(row){
      console.log(row)
      this.dialogible=true
      this.dialogImage=row.imageUrl
    },
    loadPage(){
      // setTimeout(function(){  //使用  setTimeout（）方法设定定时800毫秒
      //   window.location.reload();//页面刷新
      // },800);
      this.reload()
    },
    customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.saveFile(formData)
    },
    customRequest1 (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.saveFile1(formData)
    },
    customRequest2 (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      this.saveFile2(formData)
    },
    saveFile (formData) {
      addImg(formData).then(res=>{
        // this.imageUrl=res.data
        this.exhibitionImg=res.data
        console.log(res)
      })
    },
    saveFile1 (formData) {
      addImg(formData).then(res=>{
        // this.imageUrl=res.data
        this.aaImg.push(res.data) 
        console.log(this.aaImg)
        // console.log(aaImg)
        
        // console.log(this.lunbo)
      })
    },
    saveFile2 (formData) {
      addImg(formData).then(res=>{
        // this.imageUrl=res.data
        this.detailsImg.push(res.data) 
        console.log(this.detailsImg)
        // console.log(aaImg)
         
        // console.log(this.xiangqing)
      })
    },
    
    handleRemove(file, fileList) {
      console.log(file, fileList);
      var remove=file.url
      String.prototype.replaceAll = function(s1, s2) {
          return this.replace(new RegExp(s1, "gm"), s2);
      }
      console.log(remove.replaceAll('/','*'))
      var newRemove=remove.replaceAll('/','*')
      var params={
        imgUrl:newRemove,
        proId:this.proId
      }
      delImg(params).then(res=>{
        console.log(res)
        if(res.code==200){
          this.$message({ 
          message: '删除成功',
          type: 'success'
        })
        }
      })
    },
    handleRemove1(file, fileList) {
      console.log(file, fileList);
      var remove=file.url
      String.prototype.replaceAll = function(s1, s2) {
          return this.replace(new RegExp(s1, "gm"), s2);
      }
      console.log(remove.replaceAll('/','*'))
      var newRemove=remove.replaceAll('/','*')
      var params={
        imgUrl:newRemove,
        proId:this.proId
      }
      delImg(params).then(res=>{
        console.log(res)
        if(res.code==200){
          this.$message({ 
          message: '删除成功',
          type: 'success'
        })
        }
        this.aaImg.forEach((item,index)=>{
          if(item==file.url){
            this.aaImg.splice(index)
          }
        })
      })
    },
    handleRemove2(file, fileList) {
      console.log(file, fileList);
      var remove=file.url
      String.prototype.replaceAll = function(s1, s2) {
          return this.replace(new RegExp(s1, "gm"), s2);
      }
      console.log(remove.replaceAll('/','*'))
      var newRemove=remove.replaceAll('/','*')
      var params={
        imgUrl:newRemove,
        proId:this.proId
      }
      delDetailsImg(params).then(res=>{
        console.log(res)
        if(res.code==200){
          this.$message({ 
          message: '删除成功',
          type: 'success'
        })
        }
        this.detailsImg.forEach((item,index)=>{
          if(item==file.url){
            this.detailsImg.splice(index)
          }
        })
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureCardPreview2(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    next() {
      this.current++
    },
    prev() {
      this.current--
    },
    getSearch(){
      getSearchList().then(res=>{
        this.deps=res.data
        console.log(this.deps)
      })
    },
    getList() {
      this.listLoading = true
      var params = {
        // pageConvert: true,
        pageNum: this.listQuery.pageNum,
        pageSize: this.listQuery.pageSize,
        goodsBrand: this.listQuery.goodsBrand,
        proCode: this.listQuery.proCode,
        infoName:this.listQuery.infoName,
        catId: this.depValue
      }
      commodityList(params).then(response => {
        this.list = response.content
        console.log(this.list)
        this.total = response.totalElements
        console.log(this.total)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined
      }
    },
    handleUpdate(row) {
      // this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // console.log(row.proId)
      this.proId=row.proId
      getImg1(this.proId).then(res=>{
        // console.log(res)
        this.exhibitionImg=res.imageUrl
        this.fileList.push(Object.assign({url:this.exhibitionImg}))
        console.log(this.fileList)
        // console.log(this.fileList)
        // console.log(this.fileList)
        var lunboImg=res.proPicUrl.split(",")
        this.aaImg=this.aaImg.concat(lunboImg)
        this.aaImg.forEach((item)=>{
          this.fileList1.push(Object.assign({url:item}))
        })
        var xiangqingImg=res.bf1.split(",")
        this.detailsImg=this.detailsImg.concat(xiangqingImg)
        this.detailsImg.forEach((item)=>{
          this.fileList2.push(Object.assign({url:item}))
        })
      })
       
      // this.fileList=[]
      // this.fileList1=[]
      // this.fileList2=[]
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.lunbo=this.aaImg.join(',') 
      this.xiangqing=this.detailsImg.join(',') 
      var params={
        proId:this.proId,
        imageUrl:this.exhibitionImg,
        proPicUrl:this.lunbo,
        bf1:this.xiangqing
      }
      updateImg(params).then(res=>{
        if(res.code===200){
          this.$message({
            message: '操作Success',
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getList()
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    }
  }
}
</script>
